package cn.coderdream.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.*;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.Nullable;

/**
 * 创建:  MengPeng
 * 日期:  2017/9/20 , 下午5:06.
 * 作用:  自定义倒计时
 */
public class CountdownTimeView extends View {

    private Context mContext;
    private float mRadius; //外圆半径
    private float mPadding; //边距
    private float mSecondPointWidth; //秒针宽度
    private int mColorLong; //长线的颜色
    private int mColorShort; //短线的颜色

    private Paint mPaint; //画笔

    private int time = 0;
    private int allTime = 0;

    public addOnTimeChangedListener listener;

    public void addOnTimeChangedListener(addOnTimeChangedListener listener) {
        this.listener = listener;
    }

    /**
     * 时间发生改变的监听事件
     */
    public interface addOnTimeChangedListener {
        void addOnTimeChangedListener(int time);
    }

    /**
     * 清空时间，从头开始
     */
    public void clearTime() {
        allTime = 0;
        time = 0;
    }

    /**
     * 获取当前时间，单位是秒
     *
     * @return
     */
    public int getNowTime() {
        return allTime / 20;
    }

    public void setTime(int times) {
        allTime = times * 20;
        time = times % 60 * 20;
    }

    public CountdownTimeView(Context context) {
        this(context, null);
    }

    public CountdownTimeView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        //获取自定义的属性
        obtainStyleAttrs(attrs);
        //初始化画笔
        init();
    }

    private void obtainStyleAttrs(AttributeSet attrs) {

        TypedArray array = mContext.obtainStyledAttributes(attrs, R.styleable.CountdownTimeView);
        try {


            mPadding = array.getDimension(R.styleable.CountdownTimeView_ct_padding, dp2px(5));
//            mTextSize = array.getDimension(R.styleable.CountdownTimeView_ct_text_size, sp2px(16));
//            mHourPointWidth = array.getDimension(R.styleable.CountdownTimeView_ct_hour_pointer_width, dp2px(5));
//            mMinutePointWidth = array.getDimension(R.styleable.CountdownTimeView_ct_minute_pointer_width, dp2px(3));

            mSecondPointWidth = array.getDimension(R.styleable.CountdownTimeView_ct_second_pointer_width, dp2px(2));
//            mPointRadius = (int) array.getDimension(R.styleable.CountdownTimeView_ct_pointer_corner_radius, dp2px(10));
//            mPointEndLength = array.getDimension(R.styleable.CountdownTimeView_ct_pointer_end_length, dp2px(10));
            mColorLong = array.getColor(R.styleable.CountdownTimeView_ct_scale_long_color, Color.argb(120, 0, 0, 0));

            mColorShort = array.getColor(R.styleable.CountdownTimeView_ct_scale_short_color, Color.argb(60, 0, 0, 0));
//            mHourPointColor = array.getColor(R.styleable.CountdownTimeView_ct_hour_pointer_color, Color.BLACK);
//            mMinutePointColor = array.getColor(R.styleable.CountdownTimeView_ct_minute_pointer_color, Color.BLACK);
//            mSecondPointColor = array.getColor(R.styleable.CountdownTimeView_ct_second_pointer_color, Color.RED);

        } catch (Exception e) {
            //一旦出现错误全部使用默认值
            mPadding = dp2px(10);
//            mTextSize = sp2px(16);
//            mHourPointWidth = dp2px(5);
//            mMinutePointWidth = dp2px(3);

            mSecondPointWidth = dp2px(2);
//            mPointRadius = (int) dp2px(10);
//            mPointEndLength = dp2px(10);
            mColorLong = Color.argb(225, 0, 0, 0);

            mColorShort = Color.argb(125, 0, 0, 0);
//            mHourPointColor = Color.BLACK;
//            mMinutePointColor = Color.BLACK;
//            mSecondPointColor = Color.RED;

        } finally {
            array.recycle();
        }
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     */
    public int sp2px(float spValue) {
        float fontScale = getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 将dp值转换为px值
     */
    public int dp2px(float dpValue) {
        float scale = getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5F);
    }

    /**
     * 初始化画笔
     */
    private void init() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //设置一个最小值
        int width = 800;
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        if (widthMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.UNSPECIFIED ||
                heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED) {
            try {
                throw new NoDetermineSizeException("宽和高不能全部为wrap_content");
            } catch (NoDetermineSizeException exception) {
                exception.printStackTrace();
            }
        } else {
            if (widthMode == MeasureSpec.EXACTLY) {
                width = Math.min(widthSize, width);
            }
            if (heightSize == MeasureSpec.EXACTLY) {
                width = Math.min(heightSize, width);
            }
        }

        setMeasuredDimension(width, width);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mRadius = (Math.min(w, h) - getPaddingLeft() - getPaddingRight()) / 2;
//        mPointEndLength = mRadius / 6;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.save();
        canvas.translate(getWidth() / 2, getHeight() / 2);
        //绘制表盘外圆背景
        paintCircleBackGround(canvas);
        //绘制刻度
        paintCalibration(canvas);
        //绘制中心进度圆
        paintProgress(canvas);
        //绘制中心背景
        paintCenterTimeBg(canvas);
        //绘制中心时间
        paintCenterTime(canvas);

        if (time > 1199) {
            time = 0;
        }
        time += 1;
        allTime += 1;

        if (null != listener && allTime % 20 == 0) {
            listener.addOnTimeChangedListener(allTime / 20);
        }
        postInvalidateDelayed(50);
    }

    /**
     * 绘制中心时间背景
     *
     * @param canvas
     */
    private void paintCenterTimeBg(Canvas canvas) {
        mPaint.setColor(Color.WHITE);
        mPaint.setStyle(Paint.Style.FILL);

        Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.order_time_circle_bg);

        canvas.drawBitmap(bitmap, getMeasuredWidth() / 2 - bitmap.getWidth() / 2,
                getMeasuredHeight() / 2 - bitmap.getHeight() / 2, mPaint);
    }

    /**
     * //绘制中心时间
     *
     * @param canvas
     */
    private void paintCenterTime(Canvas canvas) {
        //分钟
        int m = allTime / 20 / 60;
        //秒钟
        int s = allTime / 20 % 60;

        String minute = "";
        if (m > 9) {
            minute = m + "";
        } else {
            minute = "0" + m;
        }

        String seconds = "";

        if (s > 9) {
            seconds = s + "";
        } else {
            seconds = "0" + s;
        }

        //绘制时间
        String timeContent = minute + ":" + seconds;

        mPaint.setStrokeWidth(3);
        mPaint.setTextSize(100);
        mPaint.setColor(Color.BLACK);
        mPaint.setTextAlign(Paint.Align.LEFT);

        Rect rectTime = new Rect();
        mPaint.getTextBounds(timeContent, 0, timeContent.length(), rectTime);

        canvas.drawText(timeContent,
                getMeasuredWidth() / 2 - rectTime.width() / 2, getMeasuredHeight() / 2 + rectTime.height() / 2, mPaint);
    }

    /**
     * 绘制表盘外圆背景
     *
     * @param canvas
     */
    private void paintCircleBackGround(Canvas canvas) {
        mPaint.setColor(Color.WHITE);
        mPaint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(0, 0, mRadius, mPaint);
    }

    /**
     * 绘制刻度
     *
     * @param canvas
     */
    private void paintCalibration(Canvas canvas) {
        mPaint.setStrokeWidth(dp2px(1f));
        int lineWith = 0;

        for (int i = 0; i < 60; i++) {
            if (i % 5 == 0) { // 整点
                //整点 刻度稍长，稍粗
                lineWith = 40;
                mPaint.setColor(mColorLong);
                mPaint.setStrokeWidth(dp2px(1.5f));
//                //绘制时间
//                String timeContent = i + "";
//                mPaint.setTextSize(mTextSize);
//                Rect rectTime = new Rect();
//                mPaint.getTextBounds(timeContent, 0, timeContent.length(), rectTime);
//                mPaint.setColor(Color.BLACK);
//                canvas.save();
//                //
//                canvas.translate(0,
//                        -mRadius + dp2px(5) + lineWith + mPadding + (rectTime.bottom - rectTime.top) / 2);
//                mPaint.setStyle(Paint.Style.FILL);
//                canvas.rotate(-6 * i);
//                canvas.drawText(timeContent,
//                        -(rectTime.right + rectTime.left) / 2,
//                        -(rectTime.bottom + rectTime.top) / 2, mPaint);
//                //
//                canvas.restore();
            } else {
                lineWith = 30;
                mPaint.setColor(mColorShort);
                mPaint.setStrokeWidth(dp2px(1f));
            }

//            Log.d(TAG, "paintCalibration: seconds:" + seconds);
//            if (i <= time / 20) {
//                mPaint.setColor(Color.argb(255, 255, 221, 0));
//            }

            canvas.drawLine(0, -mRadius + mPadding, 0, -mRadius + mPadding + lineWith, mPaint);
            canvas.rotate(6);
        }


    }

    /**
     * 绘制中心进度圆
     *
     * @param canvas
     */
    private void paintProgress(Canvas canvas) {
        int angleSecond = time * 360 / 60 / 20;//每秒的角度

        RectF rectSecond = new RectF(-(mRadius - 100), -(mRadius - 100), mRadius - 100, mRadius - 100);

        mPaint.setColor(Color.argb(255, 255, 221, 0));
        mPaint.setStrokeWidth(mSecondPointWidth);
        canvas.drawArc(rectSecond, -90, angleSecond, true, mPaint);
        canvas.restore();

        //绘制进度第二层的白色圆 ， 第一层的半径大于第二层，所以出来的就是个黄色圆环
        canvas.save();
        mPaint.setColor(Color.WHITE);
        mPaint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(mRadius, mRadius, mRadius - 120, mPaint);
    }


    class NoDetermineSizeException extends Exception {
        public NoDetermineSizeException(String message) {
            super(message);
        }
    }
}
